<template>
  <q-page class="page" style="background-color: #f5f6fa">
    <BackHeader title="个人信息" fixed />

    <div class="q-mt-md q-px-md">
      <div class="flex items-center">
        <div class="q-mr-sm">
          <q-circular-progress
            show-value
            font-size="12px"
            :value="progress"
            size="50px"
            :thickness="0.18"
            color="secondary"
            track-color="grey-3"
          >
            <div class="">
              <span class="vertical-bottom" style="font-size: 14px; font-weight: bold">{{ progress }}</span
              ><span class="vertical-bottom" style="font-size: 12px; transform: scale(0.8); display: inline-block">%</span>
            </div>
          </q-circular-progress>
        </div>
        <div>
          <div class="" style="font-size: 16px; font-weight: bold">完善信息激活额度</div>
          <div class="" style="color: #999; font-size: 13px; margin-top: 2px">补充以下信息、授权位置信息用于额度评估</div>
        </div>
      </div>
      <div
        v-for="(_, num) in Math.ceil(filedList.length / 5)"
        class="q-mt-md bg-white q-px-md"
        style="border-radius: 8px; overflow: hidden"
      >
        <section v-for="(item, index) in filedList.slice(num * 5, (num + 1) * 5)" :key="item.id">
          <div @click="filedClickHandler(item)" class="flex  q-my-xs items-center justify-between no-wrap" style="padding: 10px 0;">
            <div class="q-mr-sm" style="color: #666; white-space: nowrap">{{ item.name }}</div>
            <div class="flex items-center no-wrap">
              <div class="q-mr-xs" :style="!filedLabelValues[item.filedName] ? { color: '#999' } : {}">
                {{ filedLabelValues[item.filedName]?.label ?? '请选择' }}
              </div>
              <div class="center">
                <q-icon name="arrow_forward_ios" style="font-size: 12px; color: #999" />
              </div>
            </div>
          </div>
          <div
            v-if="index < filedList.slice(num * 5, (num + 1) * 5).length - 1"
            class="line"
            style="height: 1.5px; background: #eaebec"
          ></div>
        </section>
      </div>

      <div class="q-mt-md bg-white q-px-md" style="border-radius: 8px; overflow: hidden">
        <div class="flex q-py-sm q-my-xs items-center justify-between no-wrap" @click="areaSelectClickHandler">
          <div class="q-mr-sm" style="color: #666; white-space: nowrap">所在地区</div>
          <div class="flex items-center no-wrap">
            <div class="q-mr-xs" :style="!areaName ? { color: '#999' } : {}">{{ areaName || '请选择' }}</div>
            <div class="center">
              <q-icon name="arrow_forward_ios" style="font-size: 12px; color: #999" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <div style="height: 100px"></div>
    <div class="bottom-action-box q-pa-md">
      <q-btn
        label="同意协议并认证"
        padding="none none"
        unelevated
        rounded
        @click="submit"
        :loading="loading"
        :disable="progress < 100"
        class="full-width"
        style="background-color: #FFAD13; color: #fff; padding: 8px 18px !important; font-size: 15px; font-weight: 600"
      />
    </div>

    <ActionSheet @select="filedSelectHandler" v-model:show="showActionSheet" :actions="actions" cancel-text="取消" close-on-click-action />
    <Popup position="bottom" v-model:show="areaSelectShow">
      <Area
        :model-value="areaValue || '330102'"
        @confirm="areaSelectOkHandler"
        @cancel="areaSelectShow = false"
        title="所在地区"
        :area-list="areaList"
      />
    </Popup>
  </q-page>
</template>

<script setup lang="ts">
import { getCommonInfoApi, updateSourceInfoApi } from 'src/api/info';
import BackHeader from 'src/components/BackHeader.vue';
import { useAppStore } from 'src/stores/app-store';
import { ActionSheetAction, ActionSheet, Area, Popup, showLoadingToast, showSuccessToast, showToast } from 'vant';
import { computed, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { areaList } from '@vant/area-data';
import { watchEffect } from 'vue';
import { useLocalAMap } from 'src/hooks/local_amap';
import type { MatchResult} from 'src/types/matchResult.d'
import { useMechanismStore } from 'src/stores/mechanism-store';

const route = useRoute();
const showActionSheet = ref(false);
const actions = ref<ActionSheetAction[]>([]);

const indexKeyMap: Record<number, 'province_list' | 'city_list' | 'county_list'> = {
  0: 'province_list',
  1: 'city_list',
  2: 'county_list',
};
const areaValue = ref<string>();
const areaValues = computed(() =>
  areaValue.value && areaValue.value.length === 6
    ? [`${areaValue.value.slice(0, 2)}0000`, `${areaValue.value.slice(0, 4)}00`, areaValue.value]
    : undefined,
);
const areaNames = computed(() => areaValues.value?.map((item, index) => areaList[indexKeyMap[index]][item]));
const areaName = computed(() => areaNames.value?.join('-') ?? '');
const areaSelectShow = ref(false);

const loading = ref(false)

const router = useRouter();

type FiledResData = {
  filedName: string;
  id: number;
  parentId: number;
  sortWeight: number;
  value: string;
  name: string;
  itemInfoList?: FiledResData[];
};
type LabelValue = {
  label: string;
  value: string;
};
const filedList = ref<FiledResData[]>([]);
const filedLabelValues = ref<Record<string, LabelValue | undefined>>({});
const filedValues = computed(() => Object.fromEntries(Object.entries(filedLabelValues.value).map(([key, value]) => [key, value?.value])));

const progress = computed(() => {
  if (!filedList.value.length) return 0;
  const countNum = filedList.value.length + 1;
  const selectNum = filedList.value.reduce((a, b) => (filedValues.value[b.filedName] ? a + 1 : a), 0);
  return +(((selectNum + (areaValue.value ? 1 : 0)) / countNum) * 100).toFixed(0);
});

const filedClickHandler = (filed: FiledResData) => {
  actions.value =
    filed.itemInfoList?.map((item) => ({
      name: item.name,
      filedName: filed.filedName,
      value: item.value,
    })) ?? [];
  showActionSheet.value = true;
};
const filedSelectHandler = (action: ActionSheetAction & { filedName: string; value: string }) => {
  if (!action.name) return;
  filedLabelValues.value[action.filedName] = { label: action.name, value: action.value };
};

const areaSelectClickHandler = () => {
  areaSelectShow.value = true;
};
const areaSelectOkHandler = ({ selectedOptions, selectedValues }: any) => {
  areaValue.value = selectedValues[2];
  areaSelectShow.value = false;
};


const submit = async () => {
  loading.value = true
  const res = await updateSourceInfoApi<{matchResult: MatchResult}>({...filedValues.value, cityCode: areaValue.value?.slice(0, 4)}).finally(() => loading.value = false)
  const matchResult = res.data.matchResult

  useMechanismStore().setMatchData(matchResult)
  const {pageType} = useAppStore()

  const goToWaitPage = () => {
    if (matchResult?.orderItemList?.length) {
      return router.replace({path: '/waitPage', query: route.query})
    }
    if (pageType == 'auth') {
      return router.replace({path: '/evaluateAuth', query: route.query})
    }
    return router.replace({path: '/evaluate', query: route.query})
  }
  if (pageType == 'h5_auth_download') {
    return router.replace({path: '/down', query: route.query})
  }
  goToWaitPage()


}

const initData = async () => {
  const toast = showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0,
  });
  const res = await getCommonInfoApi<{ dataList: FiledResData[] }>();
  toast.close();
  filedList.value = res.data.dataList;
};

initData();

useLocalAMap()
  .getLocalAddress()
  .then((item) => {
    areaValue.value = item.adcode;
  });
</script>

<style lang="scss" scoped>
.input-box {
  textarea {
    border: 1px solid #4461e2;
    width: 100%;
    padding: 8px;
    border-radius: 8px;
    font-size: 16px;
  }
}
.bottom-action-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  border-top: 1px solid rgba($color: #ccc, $alpha: 0.6);
}
</style>
